package com.lz.buffer.chanel;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * FileChanelTest.. Channel中维护了两个buffer
 *
 * @author Lizhong
 * @date 2019/11/27
 */
public class FileChanelTest {

    public static void method01() throws IOException {
        RandomAccessFile aFile = new RandomAccessFile("C:\\Users\\li\\Desktop\\新建文本文档 (3).txt", "rw");

        FileChannel inChannel = aFile.getChannel();
        ByteBuffer buf = ByteBuffer.allocate(48);

        // 将channel读到buf
        int bytesRead = inChannel.read(buf);
        String s1 = IOUtils.toString(buf.array(), "UTF-8");
        System.out.println(s1);

        String newData = "New String to write to file..." + System.currentTimeMillis();

        // 读完以后，准备开始写了 position=0,mark=-1
        buf.rewind();

        // 将内容写到buffer
        buf.put(newData.getBytes());

        // 写完以后读,limit=position , position= 0 mark =-1
        buf.flip();

        while (buf.hasRemaining())

        {
            // 将buffer写到文件
            inChannel.write(buf);

        }

    }

    public static void main(String[] args) throws IOException {
        method01();
    }

}
